<?php
/**
 * @author Andrew Willmott <andrew.willmott@omni-fi.net>
 * @copyright Copyright (c) 2011, Andrew Willmott
 * @license http://www.opensource.org/licenses/mit-license.php MIT Licence
 * @version 1.0
 *
 * This page includes all the common functions for your Bitcoin bank
 */

//See if the system has been setup or not
if (file_exists("passwords.inc.php")){
	//The system has been set up so we can initialise sessions and DB connections
	require('passwords.inc.php');			//Try and include the passwords file however it does not exist it is probably because the system has not yet been setup
	setSessionVariables($temporaryDirectory);	//Set our secured session variables and start a session
}


function htmlHeader($title){
	echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
	echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" ";
	echo "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
	echo "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">\n";
	echo "<head>\n\t<title>$title</title>\n";
	echo "\t<link rel=\"icon\" type=\"image/png\"  href=\"bitcoin.png\" />\n";
}


function setSessionVariables($temporaryDirectory){
	ini_set('session.save_handler', 'files');		//Set cookies to be saved to a file
	ini_set('session.save_path', '/tmp/omni-bill');		//Set the temporary path to our secure location
	ini_set('session.use_cookies', '1');			//Allow the use of cookies
	ini_set('session.cookie_secure', '1');			//Only use this cookie in a HTTPs session
	ini_set('session.use_only_cookies', '1');		//Only use cookies so we can set aditional security values on them
	ini_set('session.auto_start', '1');			//Automatically start the session
	ini_set('session.cookie_lifetime', '0');		//Could give timeout however this is inconvient for users
	ini_set('session.cookie_path', '/');			//Allow this cookie to be used on all pages on this domain
	ini_set('session.cookie_httponly', '1');		//Do not allow scripts to access the cookie
	ini_set('session.entropy_file', '/dev/urandom');	//Add some extra randomness to the session id
	ini_set('session.entropy_length', '16');		//We do not need much randomness as we are hashing the ID as well and we do not want to run out of entropy
	ini_set('session.hash_function', '1');			//Hash the session ID with SHA256 to prevent guessing of session ID
}

function dbReadConnection(){
	//See if the connection has already been set up
	if (!array_key_exists('dbread', $GLOBALS)){
		//We have not yet established a read only connection to the database 
		$GLOBALS['dbread'] = new PDO("pgsql:host=" . $GLOBALS['dbRead'] . ";port=" . $GLOBALS['dbReadPort'] . 
					";dbname=" . $GLOBALS['dbName'], $GLOBALS['dbReadUsername'], $GLOBALS['dbReadPassword']) 
					or die("<p>Unable to connect to database for read access</p>\n");
	}
	else {
		//We have already established a read only connection to the database so we can just return that to the user
	}
	return $GLOBALS['dbread'];
}
function dbWriteConnection(){
	//See if the connection has already been set up
	if (!array_key_exists('dbwrite', $GLOBALS)){
		//We have not yet established a write connection to the database 
		$GLOBALS['dbwrite'] = new PDO("pgsql:host=" . $GLOBALS['dbWrite'] . ";port=" . $GLOBALS['dbWritePort'] .
					";dbname=" . $GLOBALS['dbName'], $GLOBALS['dbWriteUsername'], $GLOBALS['dbWritePassword']) 
					or die("<p>Unable to connect to database for write access</p>\n");
	}
	else {
		//We have already established a read only connection to the database so we can just return that to the user
	}
	return $GLOBALS['dbwrite'];
}
function dbUpdateConnection(){
	//See if the connection has already been set up
	if (!array_key_exists('dbupdate', $GLOBALS)){
		//We have not yet established a write connection to the database 
		$GLOBALS['dbupdate'] = new PDO("pgsql:host=" . $GLOBALS['dbWrite'] . ";port=" . $GLOBALS['dbWritePort'] . 
					";dbname=" . $GLOBALS['dbName'], $GLOBALS['dbUpdateUsername'], $GLOBALS['dbUpdatePassword']) 
					or die("<p>Unable to connect to database for update/delete access</p>\n");
	}
	else {
		//We have already established a read only connection to the database so we can just return that to the user
	}
	return $GLOBALS['dbupdate'];
}

/**
 * This function generates a random string of 16 characters by default.  
 */
function randomString($length = 16){
	$characters = array(
	"B","C","D","F","G","H","J","K","L","M",
	"N","P","Q","R","S","T","U","V","W","X","Y","Z",);

	//make an "empty container" or array for our keys
	$keys = array();

	//first count of $keys is empty so "1", remaining count is 1-6 = total 7 times
	while(count($keys) < $length) {
	    //"0" because we use this to FIND ARRAY KEYS which has a 0 value
	    //"-1" because were only concerned of number of keys which is 32 not 33
	    //count($characters) = 33
	    $x = mt_rand(0, count($characters)-1);
	    if(!in_array($x, $keys)) {
	      $keys[] = $x;
	    }
	}

	foreach($keys as $key){
	  $random_chars .= $characters[$key];
	}
	return $random_chars;
}

/**
 * This function connects to the bitcoin backend and returns a JSON RPC connection
 */
function getBitcoinBackendConnection(){
	//See if we already have a connection
	if (!array_key_exists('bitcoinRPC', $GLOBALS)){
		//We do not allready have an RPC connection to the Bitcoin daemon
		require_once 'jsonRPCClient.php';
		$GLOBALS['bitcoinRPC'] = new jsonRPCClient('http://' . $GLOBALS['bitcoinUser'] . ':' . $GLOBALS['bitcoinPassword'] . 
			'@' . $GLOBALS['bitcoinHost'] . ':' . $GLOBALS['bitcoinPort'] . '/');
	}
	else {
		//We allready have an existing connection to the Bitcoin daemon so we can return it
	}
	return $GLOBALS['bitcoinRPC'];
}


?>